package net.chenlin.dp.ids.common.util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * web工具类
 * @author zcl<yczclcn@163.com>
 */
public class WebUtil {

    /** 请求地址结束标志 **/
    private static final String PARAM_END = "/";

    /** 请求参数结束标志 **/
    private static final String PARAM_CHAR = "?";

    /** 请求参数连接标志 **/
    private static final String PARAM_APPENG = "&";

    /** 请求参数等于标志 **/
    private static final String PARAM_EQUALS = "=";

    /**
     * 请求链接拼接参数
     * @param requestUrl 请求地址
     * @param names 拼接参数名数组
     * @param vals 拼接参数值数组
     * @return
     */
    public static String requestAppendParam(String requestUrl, String[] names, Object[] vals) {
        StringBuilder sb = new StringBuilder(requestUrl);
        if (requestUrl.endsWith(PARAM_END)) {
            sb.deleteCharAt(requestUrl.length()-1);
        }
        if (!requestUrl.endsWith(PARAM_CHAR)) {
            sb.append(PARAM_CHAR);
        }
        for (int i = 0; i < names.length; i++) {
            sb.append(names[i]).append(PARAM_EQUALS).append(vals[i]);
            if (i != (names.length-1)) {
                sb.append(PARAM_APPENG);
            }
        }
        return sb.toString();
    }

    /**
     * 是否为ajax请求
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        String header = "x-requested-with", httpRequest = "XMLHttpRequest";
        return CommonUtil.strIsNotEmpty(request.getHeader(header))
                && request.getHeader(header).equalsIgnoreCase(httpRequest);
    }

    /**
     * 页面输出
     * @param response
     * @param content
     */
    public static void write(HttpServletResponse response, String content) {
        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.println(content);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回jsonp
     * @param json
     * @return
     */
    public static String jsonp(String json) {
        return "callback(" + json + ")";
    }

    /**
     * 重定向地址
     * @param redirectUrl
     * @return
     */
    public static String redirect(String redirectUrl) {
        return "redirect:".concat(redirectUrl);
    }

    /**
     * 重定向地址
     * @param targetUrl
     * @return
     */
    public static String html(String targetUrl) {
        return targetUrl.concat(".html");
    }

}
